home *** CD-ROM | disk | FTP | other *** search
- Path: news.th-darmstadt.de!news!enno
- From: enno@inferenzsysteme.informatik.th-darmstadt.de (Enno Sandner)
- Newsgroups: comp.lang.c++
- Subject: Re: overloading stream output (<<) with a template...
- Date: 05 Jan 1996 20:15:33 GMT
- Organization: Fachbereich Informatik, TH Darmstadt
- Distribution: world
- Message-ID: <ENNO.96Jan5211533@kitz.inferenzsysteme.informatik.th-darmstadt.de>
- References: <4chkcd$n8q@ns1.arlut.utexas.edu>
- NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
- In-reply-to: Lee Crites's message of 4 Jan 1996 22:29:33 GMT
-
- In article <4chkcd$n8q@ns1.arlut.utexas.edu> Lee Crites <crites> writes:
-
- I have a template that is defined like this:
-
- template <int theType, int theLength, class T> class Stuff
-
- I would like to overload the << stream operator. It works fine for the class
- before I made it into a template, but I just can't seem to get the right
- combination of things in the declarations of the ostream function. Would some
- kind soul out there please show me the proper format for the friend declaration
- in the class and the actual ostream function declaration?
-
- The following code is an example for a generic-friend function:
-
- #include <iostream.h>
-
- template <int theType, int theLength, class T> struct Stuff {
- friend ostream& operator << (ostream&,const Stuff&);
- };
-
- template<int theType, int theLength, class T>
- inline ostream& operator << (ostream& o,const Stuff<theType,theLength,T>&) {
- return o << "STUFF";
- }
-
- int main()
- {
- Stuff<1,2,char> s;
- cout << s << endl;
- }
-
- Many compilers still use the obsolete template-type unification which force
- an exact match for the arguments of templated function.
- These compilers will complain about this code, because the generic output
- function expects an 'ostream' reference as first argument but 'cout' is an
- instance of a subclass of 'ostream'.
- The wayout is quite simple --- just have a ostream-reference to cout, ie.
- change 'main' to:
-
- int main()
- {
- Stuff<1,2,char> s;
- ostream& o=cout;
- o << s << endl;
- }
-
- Enno
-